<?php

namespace App\Services;

use App\Exceptions\InternalException;
use App\Models\Schedule;
use App\Models\ScheduleRecord;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class ScheduleRecordService
{
    public function get($search){
        $sql = ScheduleRecord::with('role')->with('user')->with('project')->with('schedule')->whereIn('type',[2,4])->where('is_review',0);
        return $sql;
    }

    public function insert($input){
        $res = [];
        foreach ($input as $k => $v) {
            if($v){
                $res[$k] = $v;
            }
        }
        try {
            if($res['type'] == 2 || $res['type'] == 4){
                $Schedule = Schedule::find($res['schedule_id']);
                $res['front_date'] = $res['type'] == 2 ? $Schedule->start_date : $Schedule->end_date;
                $res['days'] = 0;//(strtotime($res['last_date']) - strtotime($res['front_date'])) / 86400;
            }

            $data = ScheduleRecord::create($res);
            if($data){
                return $data;
            }
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

   
    public function update($input){
        $res = [];
        foreach ($input as $k => $v) {
            if($v){
                $res[$k] = $v;
            }
        }
        unset($res['id']);
        if(isset($res['is_review']) && $res['is_review'] == 1){
            $res['review_id'] = Auth::user()->id;
        }
        try {
            $res['sums'] = ScheduleRecord::where('id',$input['id'])->first()->sums + 1;
            $data = ScheduleRecord::where('id',$input['id'])->update($res);
            if($data){
                return $data;
            }
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

}